package chen.yi.component.idempotent;

import chen.yi.component.idempotent.aspect.AnnotateRepeatAspect;
import chen.yi.component.idempotent.aspect.ExpressionRepeatAspect;
import chen.yi.component.idempotent.sign.SignInterface;
import org.aspectj.weaver.tools.PointcutParser;
import org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 配置类
 * @author huat
 **/
@Configuration
public class IdempotentApplication {
    @Value("${chen-yi.repeat.aspect.expression:null}")
    private  String expression;
    @Value("${chen-yi.repeat.aspect.interval:1000}")
    private  Long interval;
    @Value("${chen-yi.repeat.aspect.messsage:不允许重复提交}")
    private  String messsage;
    @Autowired
    private SignInterface signInterface;
    @Bean
    @ConditionalOnProperty(value = "chen-yi.repeat.annotate.enabled", havingValue = "true")
    public AnnotateRepeatAspect annotateRepeatAspect() {
        return new AnnotateRepeatAspect(signInterface);
    }
    @Bean
    @ConditionalOnProperty(value = "chen-yi.repeat.aspect.enabled", havingValue = "true")
    public AspectJExpressionPointcutAdvisor aspectJExpressionPointcutAdvisor() {
        validateExpression(expression);
        AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor();
        advisor.setExpression(expression);
        advisor.setAdvice(new ExpressionRepeatAspect (signInterface,interval,messsage));
        return advisor;
    }

    private void validateExpression(String expression) {
        try {
            PointcutParser.getPointcutParserSupportingAllPrimitivesAndUsingContextClassloaderForResolution()
                    .parsePointcutExpression(expression);
        } catch (Exception e) {
            throw new IllegalArgumentException("无效的切点表达式: " + expression, e);
        }
    }
}
